<!-- 
 查看发票
 -->
<template>
  <div class="pdfCom">
    <canvas :id="'canvas' + item" v-for="item in pdfHTML" :key="item" style="width: 100%;"/>
  </div>
</template>
<script>
// 引入
const PDFJS = require("pdfjs-dist");
PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.min");

export default {
  props: {
    // 组件引入的pdf地址
    pdfUrl: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // pdfUrl: "",
      pdfDoc: null, // pdfjs 生成的对象
      pdfHTML: 0, // pdfjs 生成的对象
    };
  },
  methods: {
    init(fileUrl) {
      let _this = this;
      PDFJS.getDocument(fileUrl).then((fileContent) => {
        _this.pdfDoc = fileContent;
        _this.pdfHTML = fileContent.numPages;
        setTimeout(() => {
          _this.renderPage(fileContent.numPages);
        }, 100);
      });
    },
    renderPage(nums) {
      for (let item = 1; item <= nums; item++) {
        // 获取页面canvas节点
        let canvas = document.getElementById(`canvas${item}`);
        // 获取上下文
        const ctx = canvas.getContext("2d");
        // 获取每一页的内容
        this.pdfDoc.getPage(item).then((page) => {
          // 文件页面的视图 1倍
          const viewport = page.getViewport(2);
          // 将画布宽度设置为视图宽度
          canvas.width = viewport.width;
          canvas.height = viewport.height;

          const renderContext = {
            canvasContext: ctx,
            viewport: viewport,
          };
          console.log(renderContext);
          // 渲染页面内容：参数是canvas画布上下文，以及文件视图
          page.render(renderContext);
        });
      }
    },
  },
  mounted() {
    //解决字体问题
    const CMAP_URL = "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.943/cmaps/";
    let obj = {};
    obj.url = this.pdfUrl; //pdf文件地址，根据情景自行修改
    obj.cMapUrl = CMAP_URL;
    obj.cMapPacked = true;
    this.init(obj);
  },
};
</script>
<style lang="scss" scoped>
    .pdfCom{
        width: 100%;
        height: 550px;
    }
</style>
